package com.niiwoo.civet.trade.service.local.databackflow.listener;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.rdb.sharding.api.HintManager;
import com.dangdang.ddframe.rdb.sharding.hint.HintManagerHolder;
import com.niiwoo.civet.account.dto.common.BankCardDTO;
import com.niiwoo.civet.account.service.bankcard.BankCardDubboService;
import com.niiwoo.civet.trade.dao.entity.DataBackflowStatus;
import com.niiwoo.civet.trade.dao.mapper.DataBackflowStatusMapperExt;
import com.niiwoo.civet.trade.enums.DataBackflowStatusDataStatusEnum;
import com.niiwoo.civet.trade.enums.DataBackflowStatusDataTypeEnum;
import com.niiwoo.civet.trade.service.local.databackflow.DataBackflowService;
import com.niiwoo.civet.user.dto.request.df.BankInfoRequestDTO;
import com.niiwoo.civet.user.dto.response.UserBasicInfoResponseDTO;
import com.niiwoo.civet.user.service.UserBasicInfoDubboService;
import com.niiwoo.civet.user.service.dataflow.UserDataBackFlowDubboService;
import com.niiwoo.tripod.tiancheng.component.TianchengDataFlowService;
import com.niiwoo.tripod.tiancheng.request.df.BankInfoRequest;
import com.niiwoo.tripod.tiancheng.response.common.TianchengUapResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * @author wping
 * @Description: 银行卡回流监听器
 * @date 2018/4/18 17:19
 */
@Slf4j
@Component
public class BankInfoListener implements DataBackflowListener {

    @Autowired
    private DataBackflowStatusMapperExt dataBackflowStatusMapperExt;

    @Autowired
    private TianchengDataFlowService tianchengDataFlowService;

    @Autowired
    private DataBackflowService dataBackflowService;

    @Reference(version = "1.0.0")
    private UserDataBackFlowDubboService userDataBackFlowDubboService;

    @Reference(version = "1.0.0")
    private UserBasicInfoDubboService userBasicInfoDubboService;

    @Reference(version = "1.0.0")
    private BankCardDubboService bankCardDubboService;

    @Override
    public void handle(Long flowExecuteId, String userId, Long projectId, int currentExecuteTimes) {

        final String methodName = "银行卡信息回流监听到回流请求, flowExecuteId:" + flowExecuteId + ", userId:" + userId + ", projectId:" + projectId;
        if (flowExecuteId == null || StringUtils.isEmpty(userId) || projectId == null) {
            log.error(methodName + "-flowExecuteId/userId/projectId为空");
            return;
        }

        if (!HintManagerHolder.isMasterRouteOnly()) {
            HintManagerHolder.clear();
            HintManager hintManager = HintManager.getInstance();
            hintManager.setMasterRouteOnly();
        }
        // 查询最近一次回流状态情况
        DataBackflowStatus dataBackflowStatus = dataBackflowStatusMapperExt.selectByUserIdProjectIdWithDataType(userId, projectId, DataBackflowStatusDataTypeEnum.BANK_INFO.getType());
        if (dataBackflowStatus != null) {
            if (DataBackflowStatusDataStatusEnum.BACKFLOW_SUCCESSED.getStatus().byteValue() == dataBackflowStatus.getDataStatus().byteValue()) {
                log.info(methodName + "-数据已经回流，无需重复回流");
                return;
            }
            if (DataBackflowStatusDataStatusEnum.FAILED.getStatus().byteValue() == dataBackflowStatus.getDataStatus().byteValue()) {
                log.info(methodName + "-数据已经回流失败, 非待回流状态");
                return;
            }

            if (DataBackflowStatusDataStatusEnum.WAITING_BACKFLOW.getStatus().byteValue() == dataBackflowStatus.getDataStatus().byteValue()
                    || DataBackflowStatusDataStatusEnum.FAILED_WITH_RETRY.getStatus().byteValue() == dataBackflowStatus.getDataStatus().byteValue()) {
                try {

                    //从账户中心查询银行卡信息
                    BankCardDTO bankCardDTO = bankCardDubboService.getUserBankCardInfo(userId);
                    if (bankCardDTO == null) {
                        log.error(methodName + "-银行卡信息不存在");
                        dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, false, dataBackflowStatus, currentExecuteTimes, "银行卡信息不存在");
                        return;
                    }

                    BankInfoRequestDTO bankInfoRequestDTO = new BankInfoRequestDTO();
                    bankInfoRequestDTO.setUserId(userId.toString());
                    bankInfoRequestDTO.setRealName(bankCardDTO.getRealName());
                    bankInfoRequestDTO.setBankCardNo(bankCardDTO.getIdCard());
                    bankInfoRequestDTO.setBankNo(bankCardDTO.getBankAccountNo());
                    bankInfoRequestDTO.setBankType(bankCardDTO.getBankCode());
                    bankInfoRequestDTO.setReservedPhone(bankCardDTO.getMobileNo());
                    bankInfoRequestDTO.setUpdateTime(bankCardDTO.getUpdateTime().getTime());

                    UserBasicInfoResponseDTO userBasicInfo = userBasicInfoDubboService.getUserBasicInfo(userId);
                    if (userBasicInfo == null) {
                        log.error(methodName + "-用户基本信息表不存在");
                        dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, false, dataBackflowStatus, currentExecuteTimes, "用户基本信息表不存在");
                        return;
                    }
                    bankInfoRequestDTO.setMobilePhone(userBasicInfo.getMobileNo());

                    BankInfoRequest bankInfoRequest = new BankInfoRequest();
                    BeanUtils.copyProperties(bankInfoRequestDTO, bankInfoRequest);

                    log.info(methodName + "-天称银行卡信息回流开始，请求参数={}", JSON.toJSONString(bankInfoRequest));
                    CompletableFuture<TianchengUapResponse> completableFuture = tianchengDataFlowService.bankInfo(bankInfoRequest);
                    completableFuture.whenComplete((s, t) -> {
                        // 成功
                        if (s != null) {
                            TianchengUapResponse tianchengUapResponse = (TianchengUapResponse) s;
                            //回流成功
                            if (tianchengUapResponse.isSuccess()) {
                                log.info(methodName + "天称银行卡信息回流成功，返回报文:{}", JSON.toJSONString(tianchengUapResponse));
                                dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, true, dataBackflowStatus, currentExecuteTimes, tianchengUapResponse.getStatus() + "_" + tianchengUapResponse.getMessage());
                            } else {
                                //回流失败
                                log.info(methodName + "天称银行卡信息回流失败，返回报文:{}", JSON.toJSONString(tianchengUapResponse));
                                dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, false, dataBackflowStatus, currentExecuteTimes, tianchengUapResponse.getStatus() + "_" + tianchengUapResponse.getMessage());
                            }
                        }
                        // 异常
                        if (t != null) {
                            log.error(methodName + "天称银行卡信息回流异常，异常信息:{}", t);
                            dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, false, dataBackflowStatus, currentExecuteTimes, t.getMessage());
                        }
                    });
                } catch (Exception e) {
                    log.error(methodName + "-回流异常", e);
                    dataBackflowService.updateAndNotifyBackflowStatusChange(flowExecuteId, false, dataBackflowStatus, currentExecuteTimes, "未知异常");
                }
            }
        } else {
            log.error(methodName + "-未查询到DataBackflowStatus数据，请初始化数据...");
        }
    }

    @Override
    public boolean isBackflowSuccess(String userId, Long projectId) {
        return dataBackflowService.isBackflowSuccess(userId, projectId, DataBackflowStatusDataTypeEnum.BANK_INFO);
    }
}
